import { log } from "console";
import { ElButton } from "element-plus";
import {computed, defineComponent, onMounted, ref, watch} from "vue";
import Pagination from "~/src/components/Pagination";
import SelectMzjf from "~/src/components/SelectMzjf";
import { Steps } from "~/src/components/Steps";
import { UserInfo } from "~/src/components/UserInfo";
import Style1080 from './1080.module.scss';
import Stylevedio from './vediotop.module.scss';
import {KEEP_VIDEO_TOP, ZFLX} from '~/src/config';
import {getMzjf, mzjfyjs} from "@/api/his";
import {ItemInfo} from "@/api/typing";
import zwsj from "@/assets/images/zwsj.png";
import {closeLoading, showLoading} from "@/utils";
import router from "@/router";
import {tempStore} from "@/store/modules/temp";


export default defineComponent({
    setup: function () {
        const Style = KEEP_VIDEO_TOP ? Stylevedio : Style1080;
        const tempstore = tempStore();

        const showDatas = ref<ItemInfo[]>([]);
        const checkedIds = ref<string[]>([]);
        const checkAll = ref(false); // 控制"全选"复选框状态
        const pageSize = ref(0);
        if (KEEP_VIDEO_TOP){
            pageSize.value = 4;
        }else{
            pageSize.value = 5;
        }
        //监听器监听checkedIds的变化
        watch(() => checkedIds.value, (val) => {
            tempstore.setmzjfids(val)
        })

        const datas = ref<ItemInfo[]>([]);
        // 获取门诊缴费数据
        async function getMzjfData() {
            showLoading();
            const res = await getMzjf({})
            datas.value = res.rows!;
            // 初始化时，全选所有项目
            handleCheckAll(true);
            closeLoading() ;

        }
        getMzjfData();
        // 处理分页 返回的当前页数据
        const handlePageChange = (Datas: any) => {
            showDatas.value = Datas;
        };

        // 单个项目勾选处理
        const handleItemCheck = (id: string) => {
            if (checkedIds.value.includes(id)) {
                // 取消勾选
                checkedIds.value = checkedIds.value.filter(item => item !== id);
                checkAll.value = false; // 有项目取消勾选，全选状态应为false
            } else {
                // 勾选
                checkedIds.value = [...checkedIds.value, id];
                // 检查是否所有项目都被勾选
                checkAll.value = checkedIds.value.length === datas.value.length;
            }
        };

        // 全选/取消全选处理
        const handleCheckAll = (checked: boolean) => {
            checkAll.value = checked; // 同步步更新全选框状态
            if (checkAll.value) {
                // 全选：选中所有项目
                checkedIds.value = datas.value.map(item => item.id);
            } else {
                // 取消全选：清空所有选中
                checkedIds.value = [];
            }

        };



        // 计算选中的总金额
        const totalAmount = computed(() => {
            return checkedIds.value.reduce((sum, id) => {
                const item = datas.value.find(item => item.id === id);
                return sum + (item ? Number(item.money) : 0);
            }, 0).toFixed(2);
        });

        // 处理去支付
        const handlePay = async () => {
            if (checkedIds.value.length === 0){
                return;
            }
            console.log("去支付以下项目：", JSON.stringify(checkedIds.value));
            // 无医保  全自费
            if (ZFLX){
                // 预结算
                let res = await mzjfyjs({
                    ids:JSON.stringify(checkedIds.value),
                })
                tempstore.setyjsItemInfo({
                    zfje:res.rows.zfje,
                    ybje:res.rows.ybje,
                    zje:res.rows.zje,
                    lsh:res.rows.lsh,
                    orderNo:res.rows.orderNo,
                    goType:res.rows.type,
                })
                router.push({path:'/smt'})
                // 医保+自费 /自费
            }else {
                router.push({
                    path: "/selectPayType",
                    query:{
                        mzjfAmount:totalAmount.value,
                    }
                })
            }
        }
        return () => <>
            <div class={Style.top}>
                <UserInfo></UserInfo>
                <Steps></Steps>
                <div class={Style.container_mar}>
                        <div class={Style.body}>
                            {showDatas.value.length > 0 ?
                            <div>
                                {showDatas.value.map((item) => (
                                    <SelectMzjf
                                        //全选状态下，将true/false选中状态1-true/false纳入key的变化，会重新渲染组件
                                        key={`${item.id}-${checkedIds.value.includes(item.id)}`}
                                        style={{ marginTop: "28px" }}
                                        id={item.id}
                                        title={item.title}
                                        money={item.money}
                                        jzks={item?.jzks}
                                        jzsj={item?.jzsj}
                                        checked={checkedIds.value.includes(item.id)}
                                        onHandleClick={(id) => handleItemCheck(id)}
                                        showCheckbox={true}  // 传入 false 隐藏复选框
                                    ></SelectMzjf>
                                ))}
                            </div>:
                                <img src={zwsj} style={{width: '70%', height:'480px' }}/>
                            }
                        </div>
                    <Pagination
                        style={{ marginTop: "20px", padding: "0 64px", marginBottom: "10px" }}
                        pageSize={pageSize.value}
                        Data={datas.value}
                        onPageChange={handlePageChange}
                    ></Pagination>
                    <div class={Style.body}>
                        <SelectMzjf
                            key={`${checkAll.value}`}// 在两种状态下切换true/false，会重新渲染组件
                            style={{ marginTop: "28px" }}
                            totalAmount={totalAmount.value}
                            checkedAll={checkAll.value}
                            checkedCount={checkedIds.value.length}
                            onCheckAllChange={(checked) => handleCheckAll(checked)}
                            showCheckbox={true}  // 传入 false 隐藏复选框
                        >
                            {{
                                btn: () => (
                                    <div class="mainZyyjBtn_zy">
                                        <ElButton class={[Style.zyyjbtn]} type="success"
                                                  onClick={() => {handlePay()}}>
                                            去支付
                                        </ElButton>
                                    </div>
                                )
                            }}
                        </SelectMzjf>
                    </div>
                </div>
            </div>
        </>;
    }
})
